package com.example.demo.dao.base;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;

public final class LambdaUtils {

    /**
     * 将 SFunction 转换成对应的属性名（驼峰）
     * 例：User::getUserName -> userName
     */
    public static <T, R> String getPropertyName(SFunction<T, R> fn) {
        SerializedLambda lambda = getSerializedLambda(fn);
        String methodName = lambda.getImplMethodName();
        if (methodName.startsWith("get") || methodName.startsWith("set")) {
            return Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
        }
        if (methodName.startsWith("is")) {
            return Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3);
        }
        throw new IllegalArgumentException("Not a getter/setter method: " + methodName);
    }

    /**
     * 将 SFunction 转换成数据库列名（下划线）
     * 例：User::getUserName -> user_name
     */
    public static <T, R> String getColumn(SFunction<T, R> fn) {
        return camelToUnderline(getPropertyName(fn));
    }

    /* ---------- 内部工具 ---------- */
    private static SerializedLambda getSerializedLambda(Serializable fn) {
        try {
            Method method = fn.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(true);
            return (SerializedLambda) method.invoke(fn);
        } catch (Exception e) {
            throw new RuntimeException("获取 SerializedLambda 失败", e);
        }
    }

    public static String camelToUnderline(String camel) {
        StringBuilder sb = new StringBuilder();
        for (char c : camel.toCharArray()) {
            if (Character.isUpperCase(c)) {
                sb.append('_').append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        // 去掉第一个可能的前导 _
        return sb.length() > 0 && sb.charAt(0) == '_' ? sb.substring(1) : sb.toString();
    }

    private LambdaUtils() {}
}